package com.syn.michat.controller;

import com.alibaba.fastjson.JSON;
import com.syn.michat.constant.ErrorContants;
import com.syn.michat.model.ResponseEntity;
import com.syn.michat.util.ResponseErrorUtil;
import com.syn.michat.util.exception.ClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;

@RestController
@RequestMapping(value = "/file",produces = "application/json;charset=UTF-8")
public class FileController {
    // 上传路径
    @Value("${file_upload_path}")
    private String uploadPath;

    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        String fileName = "";
        try {
            fileName = this.upload2(file);
        } catch (ClientException e) {
            return JSON.toJSONString(ResponseErrorUtil.convertException(e));
        } catch (Exception e) {
            return JSON.toJSONString(ResponseErrorUtil.convertException(e));
        }

        HashMap<String, Object> map = new HashMap();
        map.put("fileName", fileName);
        ResponseEntity entity = new ResponseEntity(map);

        return JSON.toJSONString(entity);
    }

    private String upload2(MultipartFile file) throws ClientException, Exception {
        if (file.isEmpty()) {
            throw new ClientException(ErrorContants.PARAMETER_ERROR, "文件为空");
        }

        String fileName = file.getOriginalFilename();
        System.out.println("上传文件名：" + fileName);

        File dest = new File(uploadPath + fileName);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        file.transferTo(dest);

//        return dest.getAbsolutePath();
        return fileName;
    }
}
